import { BASE_URL, DOMAIN_NAME } from './config.js'

const request = (() => {
  // 基础请求方法
  function _send_request(method, url, postData = {}, isDelay = false, isForm = false, hideLoading = false, chatId = null) {
    if (!hideLoading) {
      request.showLoading();
    }

    const token = uni.getStorageSync('aichat_token');
    const headers = {
      'content-type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
      'Authorization': token ? `Bearer ${token}` : '',
    };

    // 如果有chatId，添加到header
    if (chatId) {
      headers.chatID = chatId;
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        data: postData,
        header: headers,
        method: method,
        success: (res) => {
          if (!hideLoading) {
            uni.hideLoading();
          }
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            request.toast(`请求失败，状态码：${res.statusCode}`);
            reject(res);
          }
        },
        fail: (error) => {
          if (!hideLoading) {
            uni.hideLoading();
          }
          request.toast("网络不给力，请稍后再试~");
          reject(error);
        }
      });
    });
  }

  return {
    // 工具方法
    toast(text, duration = 2000, success = false) {
      uni.showToast({
        title: text || "出错啦~",
        icon: success ? 'success' : 'none',
        duration: duration
      });
    },

    showLoading(title = '请稍候...', mask = true) {
      uni.showLoading({
        mask: mask,
        title: title
      });
    },

    modal(title, content, showCancel, callback, confirmColor = "#5677fc", confirmText = "确定") {
      uni.showModal({
        title: title || '提示',
        content: content,
        showCancel: showCancel,
        cancelColor: "#555",
        confirmColor: confirmColor,
        confirmText: confirmText,
        success(res) {
          if (res.confirm) {
            callback && callback(true);
          } else {
            callback && callback(false);
          }
        }
      });
    },

    // 请求方法
    get(url, params = {}, isDelay = false, isForm = false, hideLoading = false) {
      return _send_request('GET', url, params, isDelay, isForm, hideLoading);
    },

    post(url, data = {}, isDelay = false, isForm = false, hideLoading = false, chatId = null) {
      return _send_request('POST', url, data, isDelay, isForm, hideLoading, chatId);
    },

    put(url, data = {}, isDelay = false, isForm = false, hideLoading = false) {
      return _send_request('PUT', url, data, isDelay, isForm, hideLoading);
    },

    delete(url, data = {}, isDelay = false, isForm = false, hideLoading = false) {
      return _send_request('DELETE', url, data, isDelay, isForm, hideLoading);
    }
  };
})();

// WebSocket封装
const socket = (() => {
  let socketTask = null;
  let reconnectAttempts = 0;
  const MAX_RECONNECT_ATTEMPTS = 5;
  const RECONNECT_INTERVAL = 3000;

  function _convertToWebSocketUrl(domain) {
    if (domain.startsWith('http://')) {
      return domain.replace('http://', 'ws://');
    } else if (domain.startsWith('https://')) {
      return domain.replace('https://', 'wss://');
    }
    return `ws://${domain}`;
  }

  function send(data) {
    if (socketTask) {
      try {
        socketTask.send({
          data: JSON.stringify(data),
          fail: (error) => {
            console.error('发送消息失败:', error);
            uni.showToast({
              title: '消息发送失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('消息格式化失败:', error);
      }
    }
  }

  function reconnect(e, onMessageCallback) {
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      reconnectAttempts++;
      console.log(`尝试第${reconnectAttempts}次重连...`);
      setTimeout(() => {
        init(e, onMessageCallback);
      }, RECONNECT_INTERVAL);
    } else {
      console.error('WebSocket重连次数超过限制');
      uni.showToast({
        title: '连接服务器失败，请检查网络后重试',
        icon: 'none',
        duration: 3000
      });
      reconnectAttempts = 0;
    }
  }

  function init(e, onMessageCallback) {
    // 如果已经存在连接，先关闭
    if (socketTask) {
      try {
        socketTask.close();
      } catch (err) {
        console.error('关闭现有WebSocket连接失败:', err);
      }
      socketTask = null;
    }

    const ws_url = `${_convertToWebSocketUrl(DOMAIN_NAME)}/ws`;
    try {
      socketTask = uni.connectSocket({
        url: ws_url,
        success: () => {
          console.log("WebSocket连接创建成功!");
        },
        fail: (error) => {
          console.error('WebSocket连接创建失败:', error);
          uni.showToast({
            title: 'WebSocket连接失败，请检查网络',
            icon: 'none'
          });
          reconnect(e, onMessageCallback);
        }
      });

      socketTask.onOpen(() => {
        console.log('WebSocket连接已打开');
        reconnectAttempts = 0; // 重置重连次数
        send(e);
      });

      socketTask.onClose((res) => {
        console.log('WebSocket连接关闭！', res);
        reconnect(e, onMessageCallback);
      });

      socketTask.onError((error) => {
        console.error('WebSocket发生错误:', error);
        reconnect(e, onMessageCallback);
      });

      socketTask.onMessage((res) => {
        try {
          const { data } = res;
          if (data === 'ping') {
            send('pong');
          } else {
            const res_data = JSON.parse(data);
            onMessageCallback && onMessageCallback(res_data);
          }
        } catch (error) {
          console.error('WebSocket消息处理错误:', error);
        }
      });
    } catch (error) {
      console.error('WebSocket初始化失败:', error);
      reconnect(e, onMessageCallback);
    }
  }

  return {
    init,
    send
  };
})();

export { request, socket };